package com.hjw.httpclient.retry;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 重试类：主要是针对响应状态码进行重试（请求可达）
 * 400/500
 *
 * @author hjwStrart
 * @time 2022-11-23 20:09
 * @version: 1.0
 */
@Component
public class MyRetryResponseCode {

    private RequestConfig requestConfig = null;
    private PoolingHttpClientConnectionManager cm = null;

    /*
    @Autowired
    private MyRetryStrategy myRetryStrategy;
     注意：使用junit单元测试获取不到IOC容器中的Bean实例
     */
    private MyRetryStrategy myRetryStrategy = new MyRetryStrategy(3,1000);




    @Before
    public void init() {
        requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)
                .setSocketTimeout(3000)
                .setConnectionRequestTimeout(5000)
                .build();
        cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(20);
        cm.setDefaultMaxPerRoute(2);
    }

    @Test
    public void method() throws Exception {

        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create()
//                .setRetryHandler(null)
                .setConnectionManager(cm)
                .setServiceUnavailableRetryStrategy(myRetryStrategy)
                .setDefaultRequestConfig(requestConfig)
                .build();
        String urlStr = "http://localhost:8080/form/get";
        URIBuilder uriBuilder = new URIBuilder(urlStr);
        uriBuilder.addParameter("userName", "黄嘉威");
//        uriBuilder.addParameter("userPwd", "admin");
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        CloseableHttpResponse execute = closeableHttpClient.execute(httpGet);
        if (execute.getStatusLine().getStatusCode() == 200) {
            System.out.println("请求成功！！！");
        }
    }
}
